﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net;
using System.IO;

using EHTWebsite.Code;
/// <summary>
/// CuongBH - 08/12/2011
/// </summary>
public partial class Administrator_AdminNews : System.Web.UI.Page
{
    private Int32 pageIndex = 1;
    private Int32 pageSize = 20;
    private Int32 totalRecord;
    public Int32 DanhMucTinTucID = HangSo.DEFAULT_ID;

    private DataTable dtDanhmuctintuc = new DataTable();

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            DanhMucTinTucID = Int32.Parse(Request.QueryString["DanhMucTinTucID"].ToString());
        }
        catch (Exception)
        {
            DanhMucTinTucID = HangSo.DEFAULT_ID;
        }

        try
        {
            pageIndex = Int32.Parse(Request.QueryString["PageIndex"].ToString());
        }
        catch (Exception)
        {
            pageIndex = 1;
        }

        pageSize = this.PaggingControl1.PageSize;

        if (!Page.IsPostBack)
        {
            dtDanhmuctintuc = DanhMucTinTucProvider.GetDanhsachtintucForBackEnd().Tables[0];
            LoadNews(DanhMucTinTucID);
            CreateTreeViewCategory();
        }

    }

    /// <summary>
    /// Load dl cho repeater
    /// </summary>
    /// <param name="DanhMucTinTucID"></param>
    private void LoadNews(Int32 danhMucTinTucID)
    {
        DataSet dsTinTucs = TinTucProvider.GetTintucbyDanhMucTinTucID(danhMucTinTucID,pageIndex,pageSize,out totalRecord); ;
        rpTinTuc.DataSource = dsTinTucs;
        rpTinTuc.DataBind();
        foreach (RepeaterItem item in rpTinTuc.Items)
        {
            CheckBox ckPublish = (CheckBox)item.FindControl("ckPublish");

            //Hiện biểu tượng tương ứng với trạng thái Publish
            if (ckPublish.Checked == false)
            {
                ((ImageButton)item.FindControl("btnPublish")).ImageUrl = "Templates/Images/unpublish.jpg";
            }
            else
            {
                ((ImageButton)item.FindControl("btnPublish")).ImageUrl = "Templates/Images/btncheck.png";
            }
        }

        this.PaggingControl1.PageIndex = pageIndex;
        this.PaggingControl1.TotalRecord = totalRecord;
        this.PaggingControl1.PageURL = "AdminNews.aspx?DanhMucTinTucID=" + danhMucTinTucID.ToString();
    }



    protected void rpTinTuc_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        String cmdName = e.CommandName;
        Int32 TinTucID = 0;

        try
        {
            TinTucID = Int32.Parse(e.CommandArgument.ToString());
        }
        catch
        {
        
        }

        if (cmdName.ToLower() == "delete1")
        {
            TinTucProvider.DeleteTinTucByTinTucID(TinTucID);
            LoadNews(DanhMucTinTucID);
            Response.Redirect("AdminNews.aspx");
        }
        else if (cmdName == "publish")
        {
            TinTucProvider.ChangePublishByTinTucID(TinTucID);
            LoadNews(DanhMucTinTucID);
        }
        else if (cmdName == "change_number_of_order")
        {
            try
            {
                Int32 numberOfOrder = Int32.Parse(((TextBox)e.Item.FindControl("txtNumberOfOrder")).Text.Trim());
                TinTucProvider.UpdateNumberOfOrderByTinTucID(TinTucID, numberOfOrder);
            }
            catch (Exception ex)
            {

            }

            LoadNews(DanhMucTinTucID);

        }
        else if (cmdName == "save_all")
        {
            foreach (RepeaterItem item in rpTinTuc.Items)
            {

                Int32 numberOfOrder = Int32.Parse(((TextBox)item.FindControl("txtNumberOfOrder")).Text.Trim());
                TinTucID = Int32.Parse(((Literal)item.FindControl("ltrTinTucID")).Text.Trim());
                TinTucProvider.UpdateNumberOfOrderByTinTucID(TinTucID, numberOfOrder);
            }

            LoadNews(DanhMucTinTucID); 
        }
    }



    /// <summary>
    /// Author : chiennv
    /// CreateDate : 6/02/2012
    /// Description : Phương thức tạo TreeView
    /// <param name="source"></param>
    /// <param name="e"></param>
    private void CreateTreeViewCategory()
    {
        TreeNode level0 = new TreeNode("Danh mục tin tức", "-1");
        CreateTreeViewCategorys(level0, 0);
        trvDanhMucTinTuc.Nodes.Add(level0);
        ExpandPathOfTreeNode(trvDanhMucTinTuc.SelectedNode);
    }

    /// <summary>
    /// Author : chiennv
    /// CreateDate : 6/02/2012
    /// Description : Phương thức đệ quy tạo TreeView
    /// </summary>
    private void CreateTreeViewCategorys(TreeNode treeNode, Int32 _ChuyenMucChaID)
    {
        DataRow[] dataRowsSubCateogrys = dtDanhmuctintuc.Select("ChuyenMucChaID = " + _ChuyenMucChaID.ToString());

        Int32 amountOfSubCategory = dataRowsSubCateogrys.Count();

        //Điểm dừng đệ quy
        if (amountOfSubCategory == 0)
            return;

        TreeNode tn;

        for (Int32 i = 0; i < amountOfSubCategory; ++i)
        {
            Int32 subCategoryID = Int32.Parse(dataRowsSubCateogrys[i]["DanhMucTinTucID"].ToString());
            tn = new TreeNode(dataRowsSubCateogrys[i]["TenDanhMucTinTucVN"].ToString(), subCategoryID.ToString());
            tn.CollapseAll();
            CreateTreeViewCategorys(tn, subCategoryID);
            treeNode.ChildNodes.Add(tn);

            if (subCategoryID == DanhMucTinTucID)
            {
                tn.Select();
            }

            tn = null;
        }
    }

    /// <summary>
    /// Author : toanvt
    /// CreatedDate : 10/02/2012
    /// Description : Expand Path of TreeNode
    /// </summary>
    /// <param name="tn"></param>
    private void ExpandPathOfTreeNode(TreeNode tn)
    {
        TreeNode tmpTreeNode = tn;

        if (tn == null)
            return;

        do
        {
            tmpTreeNode.Expand();
            TreeNode tmp = tmpTreeNode;
            tmpTreeNode = null;
            tmpTreeNode = tmp.Parent;
        }
        while (tmpTreeNode != null);
    }

    /// <summary>
    /// Kiểm tra xem file có tồn tại trên hệ thống hay chưa
    /// </summary>
    /// <param name="url">Đường dẫn file</param>
    /// <returns>Kết quả là True nếu file tồn tại và ngược lại trả về false</returns>
    private bool RemoteFileExists(string url)
    {
        bool result = false;
        using (System.Net.WebClient client = new WebClient())
        {
            try
            {
                Stream stream = client.OpenRead(url);
                if (stream != null)
                {
                    result = true;
                }
                else
                {
                    result = false;
                }
            }
            catch
            {
                //Any exception will returns false.
                result = false;
            }
        }
        return result;
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Administrator/AdminNewsIU.aspx?DanhMucTinTucID="+DanhMucTinTucID);
    }
   

    protected void trvDanhMucTinTuc_SelectedNodeChanged(object sender, EventArgs e)
    {
        Response.Redirect("~/Administrator/AdminNews.aspx?DanhMucTinTucID=" + this.trvDanhMucTinTuc.SelectedNode.Value);
    }
}
